<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/8/14
 * Time: 15:39
 */

namespace App\Service;

use App\Models\Config;
use Illuminate\Http\Response;

class ConfigService
{
    /**
     * 获取配置列表
     * @param array $params
     * @param string $orderBy
     * @param string $sort
     * @return \Illuminate\Http\JsonResponse
     */
    public static function getList($params = [],$orderBy = 'id',$sort = 'DESC')
    {
        $where = [];
//        $posterModel = new Poster();
        $list = Config::where($where)->orderBy($orderBy,$sort)->get()->toArray();

        return Response()->json(['code'=>200,'msg'=>'获取成功','data'=>$list]);
    }

    /**
     * 通过ID获取配置
     * @param int $Id
     * @return array
     */
    public static function getConfigById($id = 0)
    {
        $info = Config::where('id', $id)->first(['id', 'site_name', 'logo_src', 'notice', 'nf_price', 'jt_price', 'created_at', 'nf_name', 'jt_name', 'nf_num', 'jt_num', 'updated_at']);
        $info = $info ? $info->toArray() : [];
        return Response()->json(['code' => 200, 'msg' => '获取成功', 'data' => $info]);
    }

    /**
     * 修改
     * @param array $params
     * @return \Illuminate\Http\JsonResponse
     */
    public static function edit($params = [])
    {
        try{
            $info = Config::where('id',intval($params['id']))->first();
            if(!$info){
                throw new \Exception('配置不存在');
            }
            $info->site_name = trim($params['site_name']);
            $info->logo_src = trim($params['logo_src']);
            $info->notice = $params['notice'];
            $info->nf_price = floatval($params['nf_price']);
            $info->jt_price = floatval($params['jt_price']);
            $info->nf_name = trim($params['nf_name']);
            $info->jt_name = trim($params['jt_name']);
            $info->nf_num = intval($params['nf_num']) ?: 0;
            $info->jt_num = intval($params['jt_num']) ?: 0;
            $save = $info->save();
            if(!$save){
                throw new \Exception('修改失败');
            }
        }catch(\Exception $e){
            return Response()->json(['code'=>201,'msg'=>$e->getMessage()]);
        }
        return Response()->json(['code'=>200,'msg'=>'修改成功']);
    }

    public static function getNotice()
    {
        $info = Config::where('id',1)->value('notice');
        return Response()->json(['code'=>200,'msg'=>'获取成功','data'=>$info]);
    }

     public static function getPrice()
     {
        $info = Config::where('id',1)->first(['nf_price','jt_price','nf_name','jt_name','nf_num','jt_num']);
        return Response()->json(['code'=>200,'msg'=>'获取成功','data'=>$info]);
     }

}
